﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using SeeSharpTools.JY.Socket.ValueHelper;

namespace SimpleTCPServer
{
    public partial class Server : Form
    {
        Socket socketWatch = null;//负责监听的套接字
        bool check = true;
        public Server()
        {
            InitializeComponent();
        }

        private void btn_ServerOn_Click(object sender, EventArgs e)
        {
            try
            {
                //创建服务端负责监听的套接字，参数（IPV4寻址协议，使用流格式，使用Tcp传输协议）  
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ////创建监听SOCKET 
                ////socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ////设置SOCKET允许多个SOCKET访问同一个本地IP地址和端口号 
                //socketWatch.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                //获得文本框中IP地址对象  
                IPAddress address = IPAddress.Parse(textIP.Text);
                //获取端口号  
                IPEndPoint endpoint = new IPEndPoint(address, Convert.ToInt32(textPort.Text));
                //将负责监听的套接字绑定到唯一的IP和端口上  
                socketWatch.Bind(endpoint);
                //设置监听队列的长度，意思就是同时发送请求只能10个  
                socketWatch.Listen(10);
                //创建负责监听的线程，并传入监听的方法  
                Thread threadWatch = new Thread(WatchConnecting);
                threadWatch.IsBackground = true;//设置为后台线程，只要前台的一结束，那么程序就结束  
                threadWatch.Start();//启动线程  
                textState.AppendText("服务器启动" + "\r\n");
                btn_ServerOn.Enabled = false;
                check = true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void WatchConnecting()
        {
            Control.CheckForIllegalCrossThreadCalls = false;//取消線程保護
                                                            //开始监听客户端连接请求，注意：Accept方法会阻断当时线程  
            Socket sokConnection = socketWatch.Accept();
            this.textState.AppendText("Host" + this.textIP.Text + "Port" + this.textPort.Text + "Start Listen......\r\n");

            if (sokConnection.Connected)
            {
                try
                {
                    while (check)
                    {
                        //生成50个随机数字
                        double[] randonWave = new double[500];
                        Random r = new Random();
                        for (int i = 0; i < randonWave.Length; i++)
                        {
                            randonWave[i] = r.NextDouble() * i;
                        }
                        //将随机数组变成字节形式,大端方式
                        byte[] sendData2 = BigEndianValueHelper.GetBytes(randonWave);
                        //将数组字节的长度变为字节形式，大端方式
                        byte[] sendData1 = BigEndianValueHelper.GetBytes(sendData2.Length);
                        //发送下次接受的字节长度
                        sokConnection.Send(sendData1);
                        //发送数据
                        sokConnection.Send(sendData2);
                        Action act = () => easyChart1.Plot(randonWave);
                        easyChart1.Invoke(act);//这个才是同步的
                        Thread.Sleep(500);
                    }
                    sokConnection.Close();
                    socketWatch.Dispose();

                }
                catch (Exception)
                {

                    // throw;
                }

            }
        }

        private void btn_Send_Client_Click(object sender, EventArgs e)
        {
            check = false;
            btn_ServerOn.Enabled = true;
            
        }
    }
}
